from constants import *
from planet import *
import random

class Galaxy(object):

    def __init__(self,game):
        self.game = game
        self.planets = []
        
    def _roundToNearestSquare(self,x):
        num = 0
        while num*num < x:
            num += 1
            
        return (num-1)*(num-1)
        
        
    def new(self,seed):
        # initialize the random seed
        random.seed(seed)
        
        #set the number of planets and create them
        numPlanets = random.randint(GALAXY_MIN_PLANETS,GALAXY_MAX_PLANETS)
        
        # round to nearest square
        numPlanets = self._roundToNearestSquare(numPlanets)

        self.planets = []
        for i in range(numPlanets):
            self.planets.append(Planet(random.random()))
        
        # the reason why the position is set here and not in the planet constructor
        # is that the galaxy can control all the planets at once, ensuring a uniform
        # distribution (or at least non overlapping planets).
        # Positioning the planets uniformly
        side = int(sqrt(len(self.planets)))
        i = 0
        for y in range(side):
            for x in range(side):
                if i<len(self.planets):
                    xcoord = int(random.uniform((GALAXY_SIZE/(side+1))*x,(GALAXY_SIZE/(side+1))*x+(GALAXY_SIZE/(side+2))))
                    ycoord = int(random.uniform((GALAXY_SIZE/(side+1))*y,(GALAXY_SIZE/(side+1))*y+(GALAXY_SIZE/(side+2)))) 
                    self.planets[i].position = (xcoord+15,ycoord+15)
                    i += 1
                    
        
        # TODO: create Player and Enemy home planets (with some population, resources and a base)
        # in a meaningful way, for example at the two most distant planets
        playerBase = self.planets[0]
        playerBase.owner = OWNER_PLAYER
        playerBase.minerals = random.randint(50,200)
        playerBase.organics = random.randint(50,200)
        playerBase.population = playerBase.minPopulationSize
        area = random.choice(playerBase.areas.values())
        area.clear()
        playerBase.build(BUILDING_BASE,area)  
        playerBase.buildShip()
         
        enemyBase = self.planets[len(self.planets)-1]
        enemyBase.owner = OWNER_ENEMY
        enemyBase.minerals = random.randint(20,200)
        enemyBase.organics = random.randint(20,200)
        enemyBase.population = enemyBase.minPopulationSize
        area = random.choice(enemyBase.areas.values())
        area.clear()
        enemyBase.build(BUILDING_BASE,area)  
        enemyBase.buildShip()
                
        print "Galaxy - new galaxy created"
        return True
        
        
    def load(self,filename):
        print "Galaxy - loaded from file " + filename
        return True
        
    def update(self):
        #print "Galaxy - updating"
        for planet in self.planets:
            planet.update()
            

        
        
